package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.bo.ResetBO;
import com.cskaoyan.bean.pojo.MallAdmin;
import com.cskaoyan.bean.pojo.MallCategoryExample;
import com.cskaoyan.bean.pojo.MallCoupon;
import com.cskaoyan.bean.pojo.MallUser;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.service.UserService;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.util.Md5Util;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Random;

/**
 * @author: harveyliu
 * @description: 用来处理用户登录登出等请求操作
 * @time: 2021/7/12 11:08
 */
@RestController
@RequestMapping("wx/auth")
public class WxAuthController {

    String numberStr = "";

    @Autowired
    AliyunComponent aliyunComponent;

    @Autowired
    UserService userService;

    @SneakyThrows
    @PostMapping("login")
    public BaseRespVo login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");

        // 使用MD5来进行加密
        String passwordMd5 = Md5Util.getMd5(password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(new MallToken(username, passwordMd5, "wx"));
        MallUser user = (MallUser) subject.getPrincipal();

        if (user != null) {
            WxUserInfoBeanVO wxUserInfoBeanVO = new WxUserInfoBeanVO(user.getNickname(), user.getAvatar());
            long timeout = subject.getSession().getTimeout();
            Date date = new Date(timeout);
            String expiredTime = date.toLocaleString();
            WxLoginVO wxLoginVO = new WxLoginVO(wxUserInfoBeanVO, expiredTime, (String) subject.getSession().getId());
            return BaseRespVo.ok(wxLoginVO);
        } else { //登录失败
            BaseRespVo<String> baseRespVo = new BaseRespVo<>(null, "用户帐号或密码不正确", 605);
            return baseRespVo;
        }

        //return BaseRespVo.ok("1ec6b132-c3b3-4ef7-b8f4-fcdb88889bb8");
    }

    @PostMapping("/logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @PostMapping("/regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody RegCaptchaVO regCaptchaVO) {
        numberStr = "";
        for (int i = 0; i < 5; i++) {
            Random random = new Random();
            int number = random.nextInt(9);
            numberStr = numberStr + number;
        }
        aliyunComponent.sendMsg(regCaptchaVO.getMobile(), numberStr);
        SecurityUtils.getSubject().getSession().setAttribute("verifyCode", numberStr);
//        request.getServletContext().setAttribute("verifyCode", "654321");
        return BaseRespVo.ok();
    }

    @SneakyThrows
    @PostMapping("/register")
    public BaseRespVo register(@RequestBody RegisterVO registerVO) {
        Integer status = userService.queryUserByMobilePhoneOrUsername(registerVO.getMobile(), registerVO.getUsername());
        if (status == 1) {
            return BaseRespVo.fail("该手机号已经被注册!");
        }
        if (status == 2) {
            return BaseRespVo.fail("该用户名已经被注册!");
        }
        if (numberStr.equals("")) {
            return BaseRespVo.fail("还没发送验证码!");
        }
        if (!numberStr.equals(registerVO.getCode())) {
            return BaseRespVo.fail("验证码输入有误!");
        }

        if (status == 3) {
            String password = registerVO.getPassword();
            String passwordMD5 = Md5Util.getMd5(password);
            MallUser user = new MallUser(null, registerVO.getUsername(), passwordMD5,
                    null, null, null, null, null,
                    "测试用户", registerVO.getMobile(), "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80", registerVO.getWxCode(),
                    null, new Date(), new Date(), null);
            userService.insertUser(user);

            // TODO 执行插入User的操作后   增加上添加优惠券的方法
//            MallCoupon coupon = new MallCoupon(null, "注册优惠券", null, "新人专用", null, null, null, null, (short)1, null, null, null, null, null, null, new Date(), );
        }
        // 注册之后登录
        /*Map map = new HashMap();
        map.put("username", registerVO.getUsername());
        map.put("password", registerVO.getPassword());
        login(map);*/

        /*WxUserInfoBeanVO wxUserInfoBeanVO = new WxUserInfoBeanVO("测试用户", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        WxLoginVO wxLoginVO = new WxLoginVO();*/

        String passwordMd5 = Md5Util.getMd5(registerVO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(new MallToken(registerVO.getUsername(), passwordMd5, "wx"));
        MallUser user = (MallUser) subject.getPrincipal();

//        if (user != null) {
        WxUserInfoBeanVO wxUserInfoBeanVO = new WxUserInfoBeanVO("用户" + registerVO.getMobile(), "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80");
        long timeout = subject.getSession().getTimeout();
        Date date = new Date(timeout);
        String expiredTime = date.toLocaleString();
        WxLoginVO wxLoginVO = new WxLoginVO(wxUserInfoBeanVO, expiredTime, (String) subject.getSession().getId());
        return BaseRespVo.ok(wxLoginVO);
        /*} else { // 登录失败
            BaseRespVo<String> baseRespVo = new BaseRespVo<>(null, "用户帐号或密码不正确", 605);
            return baseRespVo;
        }*/

//        return BaseRespVo.ok("注册成功!");
    }

    @SneakyThrows
    @PostMapping("/reset")
    public BaseRespVo reset(@RequestBody ResetBO resetBO) {
        MallUser user = userService.queryUserByMobile(resetBO.getMobile());
        if (user == null) {
            return BaseRespVo.fail("输入的手机号有误!");
        }
        if (!numberStr.equals(resetBO.getCode())) {
            return BaseRespVo.fail("输入的验证码有误!");
        }
        String password = resetBO.getPassword();
        String passwordMD5 = Md5Util.getMd5(password);
        user.setPassword(passwordMD5);
        userService.updateUser(user);
        return BaseRespVo.ok("重置成功");
    }
}












